# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
import datetime

from odoo.exceptions import UserError


class HrAttendanceModifyRecord(models.Model):
    _name = 'hr.attendance.modify.record'
    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin']
    _description = '补卡'
    _order = 'id desc'
    name=fields.Char()
    employee_id=fields.Many2one('hr.employee',string=u'员工')
    record_id=fields.Many2one('hr.record')
    department_id = fields.Many2one('hr.department', compute='compute_department_id', store=True,string=u'部门')
    remark=fields.Char(string=u'备注')
    @api.depends('employee_id')
    def compute_department_id(self):
        for r in self:
            r.department_id = r.employee_id.department_id.id
    date=fields.Datetime()
    import_date=fields.Datetime(string=u'打卡时间')
    state=fields.Selection([
        ('draft','草稿'),
        ('approve', '确定'),
        ('cancel', '取消'),
    ],default='draft')

    def action_confirm(self):
        if self.state=='draft':
            if self.date:
                date_create=self.date + datetime.timedelta(hours=8)
            elif self.import_date:
                date_create=self.import_date
            else:
                raise UserError('打卡时间不能为空')
            record_id=self.env['hr.record'].create({
                'emp_id':self.employee_id.barcode,
                'card_date_time': date_create,
                'card_id':self.employee_id.pin

            })
            self.record_id=record_id.id
            self.state='approve'

    @api.model
    def create(self, vals):
        if not vals.get('name') or vals['name'] == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('hr.attendance.modify.record') or _('New')
        return super(HrAttendanceModifyRecord, self).create(vals)

    def unlink(self):
        for r in self:
            if r.state=='approve':
                raise UserError('不允许删除非草稿状态的补卡申请')
            return super(HrAttendanceModifyRecord, self).unlink()

    def action_cancel(self):
        self.state='cancel'
        if self.record_id:
            self.record_id.unlink()




